import express, { json } from 'express';
import apiRouter from './api/index.js';
import {expressjwt} from 'express-jwt';
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const app = express();
const port = 9090;

app.use(express.static(`${__dirname}/dist`));
app.use(json());
app.use('/api', apiRouter);
app.use(expressjwt({
  secret: '123456',
  algorithms: ['HS256']
}).unless({
  path: [
    '/api/v1.0/user/register', '/api/v1.0/user/login',
    '/main', '/login'
  ]
}));

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars
app.use((err, req, res, next) => {
  if (err.name === 'UnauthorizedError') {
    res.status(401).json({
      timestamp: new Date().getTime(),
      api: {version: 'v1.0', status: 401},
      result: {
        description: 'Unauthorized'
      }
    });
  } else {
    console.log(err);
  }
});

app.get('*', (req, res) =>{
  console.log('get connection');
  console.log(req.url);
  res.sendFile(`${__dirname}/dist/index.html`);
});

app.listen(port, () => {
  console.log(`http://127.0.0.1:${port}/login`);
});
